package com.xxl.job.admin.core.alarm.impl;

import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.util.DateUtil;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 企业微信告警
 *
 * @author winshu
 * @date 2020/11/13
 **/
@Component
public class WxWorkJobAlarm implements JobAlarm {

    @Value("${xxl.job.alarm.wxwork.url}")
    private String baseUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        if (StringUtils.isBlank(baseUrl)) {
            return true;
        }
        String alarmEmail = Optional.ofNullable(info.getAlarmEmail()).orElse("").trim();
        if (alarmEmail.length() == 0) {
            return true;
        }
        // 拆分，并过滤掉邮箱地址
        List<String> users = Stream.of(alarmEmail.split(",")).filter(item -> !item.contains("@")).collect(Collectors.toList());
        if (users.isEmpty()) {
            return true;
        }

        String content = buildContent(info, jobLog);
        // 处理逻辑
        for (String userId : users) {
            sendMessage(userId, content);
        }
        return true;
    }

    private void sendMessage(String userId, String content) {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("userId", userId);
        map.add("txt", content);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, null);
        restTemplate.postForEntity(baseUrl, request, String.class);
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    private String buildContent(XxlJobInfo info, XxlJobLog jobLog) {
        XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));
        return MessageFormat.format(loadWxWorkAlarmTemplate(),
                group != null ? group.getTitle() : "null",
                info.getId(),
                info.getJobDesc(),
                DateUtil.formatDateTime(jobLog.getTriggerTime()),
                jobLog.getId(),
                jobLog.getTriggerCode() == ReturnT.SUCCESS_CODE ? "" : jobLog.getTriggerMsg());
    }

    private static String loadWxWorkAlarmTemplate() {
        return I18nUtil.getString("jobconf_monitor_detail") + "：<br><br>" +
                I18nUtil.getString("jobinfo_field_jobgroup") + "：{0}<br>" +
                I18nUtil.getString("jobinfo_field_id") + "：{1,number,#}<br>" +
                I18nUtil.getString("jobinfo_field_jobdesc") + "：{2}<br>" +
                I18nUtil.getString("jobconf_monitor_alarm_title") + "：" +
                I18nUtil.getString("jobconf_monitor_alarm_type") + "<br>" +
                I18nUtil.getString("joblog_field_triggerTime") + "：{3}<br>" +
                I18nUtil.getString("joblog_name") + "ID" + "：{4,number,#}<br><br>" + "{5}";
    }

}
